package com.wishwall.auth;

import java.io.IOException;

import javax.persistence.EntityNotFoundException;

import com.sun.servicetag.UnauthorizedAccessException;
import com.wishwall.beans.UserBean;
import com.wishwall.persistence.PersistenceContext;

/**
 * 
 * @author yavor.gologanov
 *
 */
public class SecurityContext {

	public static final int PERMISSION_READ = 1;
	
	public static final int PERMISSION_EDIT = 2;
	
	/**
	 * 
	 * @param request
	 * @return
	 * @throws IOException
	 */
	public static SecurityContext createSecurityContext(PersistenceContext persistenceContext, String[] credentials) 
			throws IOException, UnauthorizedAccessException {
			
		String errMsg = "Invalid username or password!";
		
		if (credentials == null)  {
			throw new UnauthorizedAccessException(errMsg);
		}
		
		String username = credentials[0];
		String password = credentials[1];
		
		if (username == null) {
			throw new UnauthorizedAccessException(errMsg);
		}
		
		if (password == null) {
			throw new UnauthorizedAccessException(errMsg);
		}
				
		UserBean user = null;		
		try {
			user = persistenceContext.getUserManager().getUser(username);
		} catch (EntityNotFoundException e) {
			user = null;
		}
		if (user == null) {
			throw new UnauthorizedAccessException(errMsg);
		}
		
		if (!password.equals(user.getPassword())) {
			throw new UnauthorizedAccessException(errMsg);
		}
		
		SecurityContext context = new SecurityContext();
		context.userBean = user;
		return context;				
	}
	
	
	
	//---------------------------------------------------------------------------------------------
	
	private UserBean userBean = null;
	
	/**
	 * 
	 * @param persistenceContext
	 */
	private SecurityContext() {
	}
	
	/**
	 * 
	 * @return
	 */
	public UserBean getUserBean() {
		return userBean;
	}

}
